package com.giscloud.upload.service;

import com.giscloud.commons.model.Result;
import com.giscloud.redis.utils.RedisUtils;
import com.giscloud.upload.entity.Attachment;
import com.google.common.collect.Maps;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;

import java.io.InputStream;
import java.nio.file.Path;
import java.util.Date;
import java.util.Map;
import java.util.stream.Stream;

/**
 * 提供存储服务类，所有存储服务均由该类对外提供
 */
@Log4j2
public class StorageService {
    private String active;
    private Storage storage;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private AttachmentService attachmentService;

    public String getActive() {
        return active;
    }

    public void setActive(String active) {
        this.active = active;
    }

    public Storage getStorage() {
        return storage;
    }

    public void setStorage(Storage storage) {
        this.storage = storage;
    }

    /**
     * 存储一个文件对象
     *
     * @param inputStream   文件输入流
     * @param contentLength 文件长度
     * @param contentType   文件类型
     * @param fileName      文件索引名
     */
    public Result store(InputStream inputStream, long contentLength, String contentType, String fileName) {
        String key = generateKey(fileName);
        storage.store(inputStream, contentLength, contentType, key);
        String url = generateUrl(key);
        log.debug("对象相关信息：name:{},size:{},type:{},key:{},url:{}",fileName,contentLength,contentType,key,url);
        Attachment attachment = new Attachment();
        attachment.setAttachmentName(fileName);
        attachment.setAttachmentSize(Math.toIntExact(contentLength));
        attachment.setAttachmentType(contentType);
        attachment.setCreatedDt(new Date());
        attachment.setStatusCd(1);
        attachment.setKeycode(key);
        attachment.setVersion(new Date());
        attachment.setAttachmentUrl(url);
        attachment.setDownloadUrl(storage.downloadUrl(key));
        return attachmentService.save(attachment);
    }

    private String generateKey(String originalFilename) {
        int index = originalFilename.lastIndexOf('.');
        String suffix = originalFilename.substring(index);
        return redisUtils.generateOrderId()+suffix;
    }

    public Stream<Path> loadAll() {
        return storage.loadAll();
    }

    public Path load(String keyName) {
        return storage.load(keyName);
    }

    public Resource loadAsResource(String keyName) {
        return storage.loadAsResource(keyName);
    }

    public void delete(String keyName) {
        storage.delete(keyName);
    }

    private String generateUrl(String keyName) {
        return storage.generateUrl(keyName);
    }

}
